package com.caigou.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	private static Logger log = LoggerFactory.getLogger(StringUtil.class);

	/**
	 * 产生size位随机码，包括26英文字母（大写）+10个数字
	 * 
	 * @return
	 */
	public static String genRandomNumLetter(int size) {
		int maxNum = 36;
		int i;
		int count = 0;
		char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer sb = new StringBuffer("");
		Random r = new Random();
		while (count < size) {
			i = Math.abs(r.nextInt(maxNum));
			if (i >= 0 && i < str.length) {
				sb.append(str[i]);
				count++;
			}
		}
		return sb.toString();
	}
	
	public static String genRandomNum(int size) {
		int maxNum = 10;
		int i;
		int count = 0;
		char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		StringBuffer sb = new StringBuffer("");
		Random r = new Random();
		while (count < size) {
			i = Math.abs(r.nextInt(maxNum));
			if (i >= 0 && i < str.length) {
				sb.append(str[i]);
				count++;
			}
		}
		return sb.toString();
	}

	public static String genRandomLetter(int size) {
		int maxNum = 26;
		int i;
		int count = 0;
		char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
				'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		StringBuffer sb = new StringBuffer("");
		Random r = new Random();
		while (count < size) {
			i = Math.abs(r.nextInt(maxNum));
			if (i >= 0 && i < str.length) {
				sb.append(str[i]);
				count++;
			}
		}
		return sb.toString();
	}


	/**
	 * 微信参数通用签名生成，签名生成 参数名ASCII码从小到大排序
	 * @param encoding
	 * @param parameters
	 * @param key
	 * @return
	 */
	public static String createSign(String encoding,SortedMap<Object,Object> parameters,String key){
	    StringBuffer sb = new StringBuffer();
	    StringBuffer sbKey = new StringBuffer();
	    Set es = parameters.entrySet();  //所有参与传参的参数按照accsii排序（升序）
	    Iterator it = es.iterator();
	    while(it.hasNext()) {
	        Map.Entry entry = (Map.Entry)it.next();
	        String k = (String)entry.getKey();
	        Object v = entry.getValue();
	        //空值不传递，不参与签名组串
	        if(null != v && !"".equals(v)) {
	            sb.append(k + "=" + v + "&");
	            sbKey.append(k + "=" + v + "&");
	        }
	    }
	    //System.out.println("字符串:"+sb.toString());
	    sbKey=sbKey.append("key="+key);
	    log.info("字符串:"+sbKey.toString());
	    //MD5加密,结果转换为大写字符
	    String sign = Md5Util.MD5_32bit(sbKey.toString(), encoding).toUpperCase();//MD5Utils.MD5Encode(sbkey.toString(), characterEncoding).toUpperCase();
	    log.info("MD5加密值:"+sign);
	    return sb.toString()+"sign="+sign;
	}
	
	
	public static Map<String,String> sortHashMap(Map<String,String> map){
	    Map<String,String> sortedMap = new LinkedHashMap<>();
	    List<String> list = new ArrayList<>();
	    Iterator<String> item = map.keySet().iterator();
	    while(item.hasNext()){
	        list.add(item.next());
	    }
	    Collections.sort(list);
	    Iterator<String> item2 = list.iterator();
	    while(item2.hasNext()){
	        String key = item2.next();
	        sortedMap.put(key,map.get(key));
	    }
	    return sortedMap;
	}
	
	public static Map<String,String> sortMap(Map<String,String> map){
		SortedMap<String,String> sortMap=new TreeMap<String,String>(map);
		return sortMap;
	}
	
	/**
	 * 数值类型前面补零（共13位）
	 * @param num
	 * @return
	 */
	public static String supplementZeroGenerateThirteen(int num){
		String str = String.format("%013d", num); 
		
		return str;
	}
	
	/**
	 * 数值类型前面补零（共16位）
	 * @param num
	 * @return
	 */
	public static String supplementZeroGenerateSixteen(int num){
		String str = String.format("%016d", num); 
		
		return str;
	}
	/**
	 * 数值类型前面补零（共3位）
	 * @param num
	 * @return
	 */
	public static String supplementZeroGenerateThree(int num){
		String str = String.format("%03d", num); 
		
		return str;
	}
	
	/**
	 * 判断字符串是不是double型
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){ 
		 Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}"); 
		 Matcher isNum = pattern.matcher(str);
	     if( !isNum.matches() ){
		    return false; 
		 } 
		   return true; 
	}
	
	 public static String trim(String str, boolean nullFlag){
  	   String tempStr = null;
 
         if (str != null)
         {
             tempStr = str.trim();
         }
 
         if (nullFlag)
         {
             if ("".equals(tempStr) || "null".equals(tempStr))
             {
                 tempStr = null;
             }
         }
         else
         {
             if (tempStr == null)
             {
                 tempStr = "";
             }
         }
 
         return tempStr;
    }
	 public static String replace(String strSource, String strFrom, String strTo) {
			if(strSource==null){
				return null;
			}
			int i = 0;
			if ((i = strSource.indexOf(strFrom, i)) >= 0) {
				char[] cSrc = strSource.toCharArray();
				char[] cTo = strTo.toCharArray();
				int len = strFrom.length();
				StringBuffer buf = new StringBuffer(cSrc.length);
				buf.append(cSrc, 0, i).append(cTo);
				i += len;
				int j = i;
				while ((i = strSource.indexOf(strFrom, i)) > 0) {
					buf.append(cSrc, j, i - j).append(cTo);
					i += len;
					j = i;
				}
				buf.append(cSrc, j, cSrc.length - j);
				return buf.toString();
			}
			return strSource;
		}
 
	
	 public static String deal(String str) {
			str = replace(str, "\\", "\\\\");
			str = replace(str, "'", "\\'");
			str = replace(str, "\r", "\\r");
			str = replace(str, "\n", "\\n");
			str = replace(str, "\"", "\\\"");
			return str;
		}
	 
	 public static String GetMapToXML(Map<String,String> param){  
         StringBuffer sb = new StringBuffer();  
         sb.append("<xml>");  
         for (Map.Entry<String,String> entry : param.entrySet()) {   
                sb.append("<"+ entry.getKey() +">");  
                sb.append(entry.getValue());  
                sb.append("</"+ entry.getKey() +">");  
        }    
         sb.append("</xml>");  
         return sb.toString();  
     }
	 
	 
	 /**
	     * 不够位数的在前面补0，保留num的长度位数字
	     * @param code
	     * @return
	     */
	public static String autoGenericCode(String code, int num) {
	    String result = "";
	    // 保留num的位数
	    // 0 代表前面补充0     
	    // num 代表长度为4     
	    // d 代表参数为正数型 
	    result = String.format("%0" + num + "d", Integer.parseInt(code));
	    return result;
	}
	 
	public static void main(String[] args){
		//String a = StringUtil.supplementZeroGenerateThirteen(1000);
		double a = 32.;
		System.out.println(StringUtil.isNumeric("32."));
		System.out.println(a);
		 Map<String,String> map=new HashMap<String, String>();
		 map.put("a1","1");
		 map.put("d2", "2");
		 map.put("c3", "3");
		 map.put("a3", "4");
		 
		 Set<String> set = map.keySet();
		 for(String s:set){
		     map.get(s);
		     System.out.println("排序之前:"+s+" 值"+map.get(s));
		 }
		 System.out.println("=========================SortedMap进行处理================");
		 
		 Map<String,String> sort = StringUtil.sortHashMap(map);//StringUtil.sortMap(map);
		 Set<String> sortSet = sort.keySet();
		 for (String s :sortSet){
		     System.out.println("排序之前:"+s+" 值"+sort.get(s));
		 }
		 String str1 = "323";
		 System.out.println(StringUtil.autoGenericCode(str1, 4));
		 
		Date currentDate = new Date(System.currentTimeMillis());
		String strCurrent = DateUtil.dateToString(currentDate, "yyMM");
		System.out.println("current="+strCurrent);

		 
	}
}
